<template>
  <div>
    <el-drawer
      :wrapper-closable="false"
      append-to-body
      :title="title"
      :close-on-press-escape="true"
      size="80%"
      :modal="true"
      :visible.sync="isVisible"
      direction="rtl"
      @close="close"
    >
      <!-- 自定义步骤条 -->
      <div class="custom-steps-container">
        <div class="custom-steps">
          <template v-for="(item, index) in orderStates">
            <div
              :key="item.id"
              class="custom-step"
              :class="{
                'is-active': index === current_step,
                'is-finished': index < current_step
              }"
              @click="handleGetOrderStateData(item)"
              @mouseenter="showTooltip($event, item.name)"
              @mouseleave="hideTooltip"
            >
              <div class="step-icon">
                <i v-if="index < current_step" class="el-icon-check" />
                <span v-else>{{ index + 1 }}</span>
              </div>
              <div class="step-title">{{ getStepShortTitle(item.name) }}</div>
            </div>
            <!-- 箭头连接符 -->
            <div
              v-if="index < orderStates.length - 1"
              :key="'arrow-' + item.id"
              class="step-arrow"
              :class="{
                'is-active': index < current_step
              }"
            >
              <i class="el-icon-arrow-right" />
            </div>
          </template>
        </div>
      </div>
      <!-- 全局Tooltip -->
      <div v-show="tooltipVisible" class="global-step-tooltip" :style="tooltipStyle">
        {{ tooltipContent }}
        <div class="tooltip-arrow" />
      </div>
      <div style="margin: 15px">
        <el-row>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <span style="display: inline-block;font-size: 20px">{{ order_data.name }}</span>
            <el-tag effect="dark" size="mini" :color="order_data.crmorderstate__color">{{ order_data.crmorderstate__name }}</el-tag>
            <div style="display: block"><span style="margin-right: 10px">订单编号:{{ order_data.order_no }}</span><span>当前处理人:{{ order_data.manager }}</span></div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
            <!-- 订单相关操作 -->
            <el-button round size="mini" @click="handleShowModifyOrder">编辑</el-button>
            <el-button round size="mini" @click="handleShowOrderState">状态</el-button>
            <el-button v-if="order_data.is_pass === '请审核'" round type="success" size="mini" @click="handleShowOrderState">通过</el-button>
            <el-button v-if="order_data.is_pass === '请审核'" round type="danger" size="mini" @click="handleShowOrderState">拒绝</el-button>
            <el-button v-if="order_data.is_pass === '待审核'" round type="danger" size="mini" @click="handleShowOrderState">催审</el-button>

            <!-- 业务功能操作 -->
            <el-button
              v-if="$store.getters.roles.indexOf('crm_order_follower') !== -1"
              round
              size="mini"
              type="warning"
              icon="el-icon-s-order"
              @click="handleShowAddOrderPurchase"
            >
              跟单
            </el-button>
            <el-button round type="primary" size="mini" @click="handleShowProductionOrder">生产单</el-button>
            <el-button round type="primary" size="mini" @click="handleShowComments">工单</el-button>
            <el-button round type="primary" size="mini" @click="handleShowPaymentFile">结算</el-button>
          </el-col>
        </el-row>
        <!-- 折叠/展开按钮 -->
        <el-row style="margin-top: 10px; margin-bottom: 5px;">
          <el-button
            size="mini"
            type="text"
            style="padding: 5px 0;"
            @click="toggleDetailCollapse"
          >
            <i :class="detailCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" />
            {{ detailCollapsed ? '展开详情' : '收起详情' }}
          </el-button>
        </el-row>
        <!-- 可折叠的详情区域 -->
        <el-collapse-transition>
          <div v-show="!detailCollapsed" class="order-detail-section">
            <el-row>
              <el-alert
                :title="order_data.note"
                type="warning"
              />
            </el-row>
            <el-row>
              <el-descriptions class="margin-top" title="" :column="4" :colon="false" border>
                <el-descriptions-item v-if="order_data.customer" label="客户"><span @click="ShoweditCRMCustomer"><svg-icon :icon-class="order_data.customer.country" />{{ order_data.customer.name }}<el-icon class="el-icon-edit" /></span></el-descriptions-item>
                <el-descriptions-item label="订单日期">{{ order_data.create_at }}</el-descriptions-item>
                <el-descriptions-item label="订单金额">{{ order_data.currency }}{{ order_data.order_amount }}</el-descriptions-item>
                <el-descriptions-item v-if="order_data.customer !== undefined" label="客户分类">
                  {{ order_data.customer.crmcustomercategory__name }}
                </el-descriptions-item>
                <el-descriptions-item label="交货截止日期">{{ order_data.ending_date }}</el-descriptions-item>
                <el-descriptions-item v-if="order_data.sales_manager_name && this.$store.getters.roles.indexOf('sales_manager') !== -1" label="销售经理">{{ order_data.sales_manager_name }}</el-descriptions-item>
                <el-descriptions-item label="客户需求">{{ order_data.quote }}</el-descriptions-item>
              </el-descriptions>
            </el-row>
          </div>
        </el-collapse-transition>
        <el-row>
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <el-tab-pane label="产品列表" name="products">
              <div class="tab-content-container">
                <crmorderproduct :order_data="order_data" />
              </div>
            </el-tab-pane>
            <el-tab-pane label="物流信息" name="first">
              <div class="tab-content-container">
                <crmshippinginquiry :order_data="order_data" />
              </div>
            </el-tab-pane>
            <el-tab-pane label="附件列表" name="six">
              <div class="tab-content-container">
                <crmorderattachments :order_data="order_data" />
              </div>
            </el-tab-pane>
            <!--            <el-tab-pane label="财务信息" name="finance" v-if="this.$store.getters.roles.indexOf('finance_user') !== -1">-->
            <el-tab-pane label="财务信息" name="finance">
              <div class="tab-content-container">
                <crmorderfinance :order_data="order_data" />
              </div>
            </el-tab-pane>
            <el-tab-pane label="操作记录" name="third">
              <div class="tab-content-container">
                <crmoperationlog :order_data="order_data" />
              </div>
            </el-tab-pane>

          </el-tabs>
        </el-row>
      </div>
      <el-dialog :title="orderStateTitle" append-to-body :visible.sync="orderStateVisible" :close-on-click-modal="false" width="900px">
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="never" style="height: 100%;">
              <div slot="header" class="clearfix">
                <span style="font-weight: bold; color: #409EFF;">状态变更</span>
              </div>
              <el-form :model="orderStateStaffTemp" label-position="top" label-width="auto">
                <el-form-item label="订单状态">
                  <el-cascader
                    v-model="orderStateStaffTemp.crmorderstate_id"
                    :options="orderStates"
                    :props="{ checkStrictly: true , value: 'id', label: 'name', expandTrigger: 'hover'}"
                    clearable
                    style="width: 100%;"
                    placeholder="请选择订单状态"
                    @change="handleOrderStateChange"
                  />
                </el-form-item>
                <el-form-item label="该状态处理人">
                  <!--               <el-switch-->
                  <!--                  style="display: block; margin-top: 5px"-->
                  <!--                  v-model="orderStateStaffTemp.is_rush_order"-->
                  <!--                  active-color="#13ce66"-->
                  <!--                  inactive-color="#ff4949"-->
                  <!--                  @change="handleRushOrderChange"-->
                  <!--                  active-text="抢单"-->
                  <!--                  inactive-text="指定负责人">-->
                  <!--                </el-switch>-->
                  <el-select v-model="orderStateStaffTemp.user_id" placeholder="请选择负责人" filterable clearable style="width: 100%;">
                    <el-option
                      v-for="item in projectUsers"
                      :key="item.id"
                      :label="item.first_name + item.last_name + '(' + item.tag + ')'"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
            <el-card shadow="never" style="height: 100%;">
              <div slot="header" class="clearfix">
                <span style="font-weight: bold; color: #67C23A;">历史状态负责人</span>
              </div>
              <el-table :data="order_data.staffs" border fit highlight-current-row size="small" max-height="300">
                <el-table-column align="center" label="状态" prop="crmorderstate__name" show-overflow-tooltip />
                <el-table-column align="center" label="负责人" prop="user__first_name" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.user__first_name }}{{ scope.row.user__last_name }}
                  </template>
                </el-table-column>
                <el-table-column align="center" label="变更时间" prop="create_at" show-overflow-tooltip>
                  <template slot-scope="scope">
                    {{ scope.row.create_at }}
                  </template>
                </el-table-column>
                <!--              <el-table-column align="center" label="操作" width="300" fixed="right">-->
                <!--                <template slot-scope="scope">-->
                <!--                  <el-button v-show="!scope.row.edit" size="mini" icon="el-icon-delete" type="error"-->
                <!--                             @click="handleAction('delete', scope.row)" plain>删除-->
                <!--                  </el-button>-->
                <!--                </template>-->
                <!--              </el-table-column>-->
              </el-table>
            </el-card>
          </el-col>
        </el-row>

        <div slot="footer" class="dialog-footer" align="center">
          <el-button type="info" @click="orderStateVisible=false">取消</el-button>
          <el-button type="success" :loading="addOrderStaffloading" @click="handleAddCRMOrderStaff">保存</el-button>
        </div>
      </el-dialog>
      <el-dialog :title="orderDateFormTitle" append-to-body :visible.sync="orderDataFormVisible" class="mt-dialog">
        <el-form :model="orderDatatemp" :rules="rules" label-position="right" label-width="120px">
          <div style="display: flex; flex-wrap: wrap; justify-content: space-between;">
            <!-- 左侧列 -->
            <div style="width: 48%;">
              <el-form-item label="币种" prop="currency">
                <el-select v-model="orderDatatemp.currency" placeholder="请选择">
                  <el-option v-for="item in currencys" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="订单金额" prop="order_amount">
                <el-input v-model="orderDatatemp.order_amount" placeholder="订单金额" />
              </el-form-item>
              <el-form-item label="订单编号">
                <el-input v-model="orderDatatemp.order_no" placeholder="订单编号" />
              </el-form-item>
              <el-form-item label="订单名称" prop="name">
                <el-input v-model="orderDatatemp.name" placeholder="请输入订单名称" />
              </el-form-item>
              <el-form-item label="订单状态">
                <el-select v-model="orderDatatemp.crmorderstate_id" disabled placeholder="选择订单状态">
                  <el-option v-for="item in orderStates" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                  <i class="el-icon-info" /> 请通过"变更状态"按钮执行状态变更
                </div>
              </el-form-item>
              <el-form-item label="客户需求">
                <el-input v-model="orderDatatemp.quote" type="textarea" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="orderDatatemp.note" type="textarea" />
              </el-form-item>
            </div>
            <!-- 右侧列 -->
            <div style="width: 48%;">
              <el-form-item label="贸易方式">
                <el-input v-model="orderDatatemp.trade_type" placeholder="贸易方式" />
              </el-form-item>
              <el-form-item label="发票号">
                <el-input v-model="orderDatatemp.invoice_number" placeholder="请输入发票号" />
              </el-form-item>
              <el-form-item label="交货日期">
                <el-date-picker v-model="orderDatatemp.ending_date" align="right" type="date" placeholder="选择日期" :picker-options="pickerOptions" />
              </el-form-item>
              <el-form-item label="跟踪单号">
                <el-input v-model="orderDatatemp.tracking_number" placeholder="请输入物流跟踪单号" />
              </el-form-item>

              <el-form-item v-if="this.$store.getters.roles.indexOf('sales_manager') !== -1" label="销售经理">
                <el-select v-model="orderDatatemp.sales_manager_id" placeholder="选择销售经理" filterable clearable>
                  <el-option
                    v-for="item in projectUsers"
                    :key="item.id"
                    :label="item.first_name + item.last_name + '(' + item.tag + ')'"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
          <el-divider>自定义订单属性</el-divider>
          <div style="display: flex; flex-wrap: wrap; justify-content: space-between;">
            <el-form-item v-for="(item, index) in orderDatatemp.dynamic_attributes" :key="index" :label="item.key">
              <el-input v-model="item.value" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer" align="center">
          <el-button type="info" @click="orderDataFormVisible=false">取消</el-button>
          <el-button type="success" :loading="createloading" @click="handleModifyOrder">保存</el-button>
        </div>
      </el-dialog>
      <crmeditcustomer
        :customer_row="crmCustomerTemp"
        :doaction="action"
        :is-visible="showCrmCustomerDialog"
        @close="showCrmCustomerDialog=false"
      />
    </el-drawer>
    <crmproductionorder :order_no="productionOrderId" :order_name="productionOrderName" :visible="showProductionOrderVisible" @close="showProductionOrderVisible=false" />
    <crmticketcomments :order-id="order_data.id" :visible.sync="showCommentsVisible" @close="showCommentsVisible=false" />
    <CRMPaymentFileDrawer
      :visible="showPaymentFileVisible"
      :order_no="order_data.order_no"
      :order_name="order_data.name"
      @close="showPaymentFileVisible=false"
    />
    <!-- 跟单创建组件 -->
    <CRMAddOrderPurchase
      :visible="showAddOrderPurchaseVisible"
      :order-data="order_data"
      @close="showAddOrderPurchaseVisible=false"
      @success="handleOrderPurchaseSuccess"
    />
  </div>
</template>

<script>
import { Get as CRMGetProducts } from '@/api/crm/crmproduct'
import { Put as ModifyOrder } from '@/api/crm/crmorder'
import { Put as ModifyCustomer, Get as GetCrmCustomers } from '@/api/crm/crmcustomer'
import { Get as GetOrderStatus } from '@/api/crm/crmorderstate'
import { Post as AddOrderStaff, GetOrderStateInfo } from '@/api/crm/crmorderstaff'
import { CRMGetProjectUsers } from '@/api/crm/crmmanage'
import { currencys, countries, customer_source, relationshipOptions, getCountryLabel } from '../../../api/crm/crmcommon'
import qs from 'qs'
import Vue from 'vue'
import Crmshippinginquiry from './crmshippinginquiry'
import Crmoperationlog from './crmoperationlog'
import Crmorderproduct from './crmorderproduct'
import Crmeditcustomer from './crmeditcustomer'
import Crmorderattachments from './crmorderattachments'
import Crmorderfinance from './crmorderfinance'
import Crmproductionorder from './crmproductionorder.vue'
import Crmticketcomments from './crmticketcomments.vue'
import CRMPaymentFileDrawer from './crmpaymentfile.vue'
import CRMAddOrderPurchase from '@/components/CRMAddOrderPurchase'
Vue.directive('clickable-steps', {
  bind(el, binding) {
    // 确保 el-steps 渲染完成
    Vue.nextTick(() => {
      const steps = el.querySelectorAll('.el-step__head, .el-step__title, .el-step__description')
      steps.forEach((step, index) => {
        step.style.cursor = 'pointer' // 可选：添加鼠标手势
        step.addEventListener('click', () => {
          if (typeof binding.value === 'function') {
            binding.value(index) // 调用回调函数，并传递当前点击的步骤索引
          }
        })
      })
    })
  }
})
const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Crmorderdetail',
  components: { CRMPaymentFileDrawer, Crmticketcomments, Crmproductionorder, Crmorderfinance, Crmorderattachments, Crmeditcustomer, Crmorderproduct, Crmoperationlog, Crmshippinginquiry, CRMAddOrderPurchase },
  props: ['order_data', 'orderStates', 'showAble'],
  data() {
    return {
      title: '销售订单详情',
      getCountryLabel: getCountryLabel,
      current_step: 1,
      // orderStates: [],
      showCrmCustomerDialog: false,
      crmCustomerTitle: '修改客户信息',
      searchCustomerKey: '',
      searchCustomers: [],
      searchCustomerlistLoading: false,
      action: 'edit',
      crmCustomerTemp: {
        name: '',
        tag: [],
        company: '',
        domain: '',
        mail: '',
        phone: '',
        whatsapp: '',
        country: '',
        source: ''
      },
      projectUsers: [],
      orderstatesloading: false,
      orderStateVisible: false,
      orderStateTitle: '变更状态',
      relationshipOptions: relationshipOptions,
      orderStateStaffTemp: {
        crmorder_id: '',
        crmorderstate_id: '',
        is_rush_order: false,
        user_id: '',
        relationship: 'sales'
      },
      addOrderStaffloading: false,
      isVisible: false,
      orderDateFormTitle: '编辑订单信息',
      orderDataFormVisible: false,
      createloading: false,
      orderDatatemp: {
        id: '',
        name: '',
        is_quote: true,
        ending_date: '',
        order_no: '',
        note: '',
        trade_type: '',
        invoice_number: '',
        tracking_number: '',
        crmorderstate_id: '',
        crmcustomer_id: '',
        currency: 'USD',
        quote: '',
        sales_manager_id: '',
        dynamic_attributes: []
      },
      countries: countries,
      currencys: currencys,
      customer_source: customer_source,
      rules: {
        name: [
          { required: true, message: '请输入方便自己查询的订单名称', trigger: 'blur' },
          { min: 3, max: 120, message: '长度在 3 到120个字符', trigger: 'blur' }
        ],
        currency: [
          { required: true, message: '必须选择币种', trigger: 'blur' }
        ],
        customer_name: [
          { required: true, message: '客户名称', trigger: 'blur' },
          { min: 1, max: 120, message: '长度在 3 到120个字符', trigger: 'blur' }
        ]
      },
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '明天',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '3天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 3)
            picker.$emit('pick', date)
          }
        },
        {
          text: '一周后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        },
        {
          text: '15天后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 15)
            picker.$emit('pick', date)
          }
        },
        {
          text: '一个月后',
          onClick(picker) {
            const date = new Date()
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30)
            picker.$emit('pick', date)
          }
        }
        ]
      },
      activeName: 'products',
      products: [],
      productlistloading: true,
      kwInput: '',
      order_by: '',
      order_desc: orderMapper[0],
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      showProductionOrderVisible: false,
      productionOrderId: '',
      productionOrderName: '',
      showCommentsVisible: false,
      showPaymentFileVisible: false,
      // 跟单创建相关
      showAddOrderPurchaseVisible: false,
      // 详情折叠状态（默认折叠）
      detailCollapsed: true,
      // Tooltip相关
      tooltipVisible: false,
      tooltipContent: '',
      tooltipStyle: {}
    }
  },
  watch: {
    showAble(v) {
      this.isVisible = v
      if (v) {
        this.orderStateStaffTemp.crmorderstate_id = this.order_data.crmorderstate_id
        this.orderStateStaffTemp.crmorder_id = this.order_data.id
        this.title = this.order_data.order_no + '询盘订单详情'
        // this.handleGetProducts()
        this.handleSetStep()
      }
    }
  },
  created() {
    this.handleCRMGetProjectUsers()
  },
  methods: {
    handleAddShippingInquiry() {
      // 添加物流询价
    },
    handleSetStep() {
      // 添加空值检查，防止 orderStates 未传递或为空时报错
      if (!this.orderStates || !Array.isArray(this.orderStates)) {
        console.warn('orderStates 未定义或不是数组')
        this.current_step = -1
        return
      }

      this.current_step = this.orderStates.findIndex(state => state.id === this.order_data.crmorderstate_id)
      if (this.current_step < 0) {
        this.current_step = this.orderStates.findIndex(state => state.id === this.order_data.crmorderstate_parent_id)
      }
    },
    handleSearchCustomer() {
      this.searchCustomerlistLoading = true
      GetCrmCustomers(null, qs.stringify({
        kw: this.searchCustomerKey,
        pagesize: 10,
        project_id: this.$store.getters.projectId,
        page: 1
      }))
        .then(response => {
          this.searchCustomers = response.data.data
          this.searchCustomerlistLoading = false
        }).catch(e => {
          this.searchCustomerlistLoading = false
        })
    },
    handleSelectCustomer(row) {
      Object.keys(this.crmCustomerTemp).forEach(key => {
        if (row[key] !== undefined) this.crmCustomerTemp[key] = row[key]
      })
      this.crmCustomerTemp.id = row.id
      this.crmCustomerTemp.tag = row.tag
      this.crmCustomerTitle = '修改客户信息:' + this.crmCustomerTemp.name
      // this.orderDatatemp.crmcustomer_id = row.id
    },
    ShoweditCRMCustomer() {
      if (this.order_data.customer) {
        this.crmCustomerTemp = this.order_data.customer
        this.crmCustomerTitle = '修改客户信息:' + this.crmCustomerTemp.name
      }
      this.showCrmCustomerDialog = true
      if (this.orderDatatemp.id === '') {
        Object.keys(this.orderDatatemp).forEach(key => {
          if (this.order_data[key] !== undefined) this.orderDatatemp[key] = this.order_data[key]
        })
      }
    },
    handleCRMGetProjectUsers() {
      CRMGetProjectUsers(qs.stringify({
        pagesize: 100,
        page: 1,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.projectUsers = response.data.data
        }).catch(err => {
          console.log(err)
        })
    },
    handleModifyCustomer() {
      this.createloading = true
      ModifyCustomer(this.crmCustomerTemp.id, this.crmCustomerTemp
      ).then(response => {
        this.notify('修改成功')
        Object.keys(this.crmCustomerTemp).forEach(key => {
          if (this.crmCustomerTemp[key] !== undefined) this.order_data['customer.' + key] = this.crmCustomerTemp[key]
        })
        // 切换用户 ID
        if (this.orderDatatemp.crmcustomer_id !== this.crmCustomerTemp.id) {
          this.orderDatatemp.crmcustomer_id = this.crmCustomerTemp.id
          this.handleModifyOrder()
        }

        this.createloading = false
      }).catch(err => {
        console.log(err)
        this.createloading = false
      })
    },
    handleShowModifyOrder() {
      this.orderDateFormTitle = '编辑订单:' + this.order_data.name
      Object.keys(this.orderDatatemp).forEach(key => {
        if (this.order_data[key] !== undefined) this.orderDatatemp[key] = this.order_data[key]
      })
      // this.handleGetProducts()
      this.orderDataFormVisible = true
    },
    handleGetOrderStateInfo(row) {
      // 获取订单当前步骤状态的信息，处理人，责任人等信息
    },
    handleGetOrderStateData(item) {
      GetOrderStateInfo({ crmorderstate_id: item.id, crmorder_id: this.order_data.id }).then(response => {
        this.$message({
          showClose: true,
          dangerouslyUseHTMLString: true,
          message: response.data.html
        })
      }).catch(err => {
        console.log(err)
        this.productlistloading = false
      })
    },
    handleGetProducts() {
      this.productlistloading = true
      this.products = []
      CRMGetProducts(null, qs.stringify({
        kw: this.kwInput,
        crmorder_id: this.order_data.id,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.products = response.data.data
          this.productlistloading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.productlistloading = false
        })
    },
    handleShowProductionOrder() {
      this.showProductionOrderVisible = true
      this.productionOrderId = this.order_data.order_no
      this.productionOrderName = this.order_data.name
    },
    handleShowOrderState() {
      this.orderStateTitle = '贸易订单状态修改:' + this.order_data.name
      this.orderStateVisible = true
      this.orderStateStaffTemp.crmorderstate_id = this.order_data.crmorderstate_id
      this.orderStateStaffTemp.crmorder_id = this.order_data.id
    },
    handleOrderStateChange(value) {
      // 订单选择发生改变，获取当前状态是否有执行人
      // 查找父级对象
      const parentObj = this.orderStates.find(item => item.id === value[0])
      // 定义结果变量
      let result = null
      if (parentObj && parentObj.children) {
        // 在父级对象的子对象中查找
        result = parentObj.children.find(child => child.id === value[1])
      }
      if (result && result.manager_id) {
        this.orderStateStaffTemp.is_rush_order = false
        this.orderStateStaffTemp.user_id = result.manager_id
      } else {
        this.orderStateStaffTemp.is_rush_order = true
        this.orderStateStaffTemp.user_id = ''
      }
    },

    handleRushOrderChange(value) {
      if (value) {
        this.orderStateStaffTemp.user_id = ''
      }
    },
    handleAddCRMOrderStaff() {
      if (this.orderStateStaffTemp.user_id === '') {
        this.$message.error('请选择负责人')
        this.addOrderStaffloading = false
        return
      }
      this.addOrderStaffloading = true
      AddOrderStaff(this.orderStateStaffTemp
      ).then(response => {
        this.notify('修改成功')
        this.addOrderStaffloading = false
        this.order_data.crmorderstate__color = response.data.crmorderstate__color
        this.order_data.crmorderstate__name = response.data.crmorderstate__name
        this.order_data.crmorderstate_id = response.data.crmorderstate_id
        this.order_data.crmorderstate_parent_id = response.data.crmorderstate_parent_id
        this.handleSetStep()
        this.addOrderStaffloading = false
        this.orderStateVisible = false
      }).catch(err => {
        console.log(err)
        this.addOrderStaffloading = false
        this.orderStateVisible = false
      })
    },
    handleModifyOrder() {
      this.createloading = true
      ModifyOrder(this.orderDatatemp.id, this.orderDatatemp
      ).then(response => {
        this.notify('修改成功')
        Object.keys(this.order_data).forEach(key => {
          if (this.orderDatatemp[key] !== undefined) this.order_data[key] = this.orderDatatemp[key]
        })
        this.createloading = false
      }).catch(err => {
        console.log(err)
        this.createloading = false
      })
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    handleGetOrderState() {
      this.orderstatesloading = true
      GetOrderStatus().then(response => {
        this.orderStates = response.data.data.reverse()
        if (this.orderStates !== undefined && this.orderStates) {
          this.orderStateStaffTemp.crmorderstate_id = this.orderStates[0].id
        }
        this.orderstatesloading = false
      }).catch(err => {
        console.log(err)
        this.orderstatesloading = false
      })
    },
    close() {
      this.$emit('close')
    },
    handleShowComments() {
      this.showCommentsVisible = true
    },
    handleShowPaymentFile() {
      this.showPaymentFileVisible = true
    },
    /**
     * 显示创建跟单对话框
     */
    handleShowAddOrderPurchase() {
      this.showAddOrderPurchaseVisible = true
    },
    /**
     * 跟单创建成功处理
     * @param {Object} data - 创建成功返回的数据
     */
    handleOrderPurchaseSuccess(data) {
      this.$message.success('跟单创建成功，可前往跟单管理查看')
      this.showAddOrderPurchaseVisible = false
      // 可以在这里添加其他成功后的处理逻辑，比如刷新某些数据
    },
    /**
     * 切换详情折叠状态
     */
    toggleDetailCollapse() {
      this.detailCollapsed = !this.detailCollapsed
    },
    /**
     * 点击标签页时自动折叠详情
     */
    handleTabClick(tab) {
      // 当用户点击tabs时，自动折叠详情区域
      if (!this.detailCollapsed) {
        this.detailCollapsed = true
      }
    },
    /**
     * 获取步骤条简短标题（显示P1+最多4个中文字）
     * @param {String} name - 完整的状态名称，如 "P1初始询盘"
     * @returns {String} 简短标题，如 "P1初始"、"P2背调需求"
     */
    getStepShortTitle(name) {
      if (!name) return ''
      // 匹配 P1、P2 等开头的编号和后面的中文
      const match = name.match(/^(P\d+)(.*)/)
      if (match) {
        const prefix = match[1] // P1, P2 等
        const suffix = match[2] // 后面的文字

        // 提取中文字符（最多4个）
        const chineseChars = suffix.match(/[\u4e00-\u9fa5]/g)
        if (chineseChars && chineseChars.length > 0) {
          const displayText = chineseChars.slice(0, 4).join('')
          return prefix + displayText
        }
        return prefix // 如果没有中文，只返回P1
      }
      return name.substring(0, 6) // 如果没有P编号格式，取前6个字符
    },
    /**
     * 显示Tooltip
     * @param {Event} event - 鼠标事件
     * @param {String} content - tooltip内容
     */
    showTooltip(event, content) {
      const rect = event.currentTarget.getBoundingClientRect()
      this.tooltipContent = content
      this.tooltipStyle = {
        top: rect.top + rect.height / 2 + 'px',
        left: rect.right + 10 + 'px'
      }
      this.tooltipVisible = true
    },
    /**
     * 隐藏Tooltip
     */
    hideTooltip() {
      this.tooltipVisible = false
    }
  }
}
</script>

<style>
.el-cascader--medium {
    width: 300px!important;
  }

/* 自定义步骤条容器 - 支持横向滚动 */
.custom-steps-container {
    overflow-x: auto;
    overflow-y: hidden;
    margin-bottom: 15px;
    padding-bottom: 5px;
    position: relative;
    z-index: 1;
}

/* 滚动条样式 */
.custom-steps-container::-webkit-scrollbar {
    height: 6px;
}

.custom-steps-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.custom-steps-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.custom-steps-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 步骤条 */
.custom-steps {
    display: flex;
    align-items: center;
    background-color: #f5f7fa;
    padding: 12px 15px;
    border-radius: 6px;
    gap: 0;
    min-width: max-content;
}

/* 箭头连接符 */
.step-arrow {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 6px;
    color: #dcdfe6;
    font-size: 16px;
    transition: color 0.3s ease;
    flex-shrink: 0;
}

.step-arrow.is-active {
    color: #67c23a;
}

.step-arrow i {
    font-weight: bold;
}

/* 单个步骤项 */
.custom-step {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 6px 12px;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s ease;
    position: relative;
    background-color: #fff;
    border: 1px solid #e4e7ed;
    z-index: 1;
}

.custom-step:hover {
    background-color: #ecf5ff;
    border-color: #409eff;
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
    z-index: 10000;
}

/* 步骤图标 */
.custom-step .step-icon {
    width: 22px;
    height: 22px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    font-weight: 600;
    background-color: #e4e7ed;
    color: #909399;
    flex-shrink: 0;
    transition: all 0.3s ease;
}

/* 步骤标题 */
.custom-step .step-title {
    font-size: 13px;
    font-weight: 500;
    color: #606266;
    white-space: nowrap;
    transition: all 0.3s ease;
}

/* 已完成状态 */
.custom-step.is-finished {
    background-color: #f0f9ff;
    border-color: #67c23a;
}

.custom-step.is-finished .step-icon {
    background-color: #67c23a;
    color: #fff;
}

.custom-step.is-finished .step-title {
    color: #67c23a;
}

/* 当前激活状态 */
.custom-step.is-active {
    background-color: #ecf5ff;
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.custom-step.is-active .step-icon {
    background-color: #409eff;
    color: #fff;
    animation: pulse 1.5s ease-in-out infinite;
}

.custom-step.is-active .step-title {
    color: #409eff;
    font-weight: 600;
}

/* 脉冲动画 */
@keyframes pulse {
    0%, 100% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.1);
    }
}

/* 全局Tooltip - 使用fixed定位，最高z-index */
.global-step-tooltip {
    position: fixed;
    background-color: #303133;
    color: #fff;
    font-size: 12px;
    padding: 6px 10px;
    border-radius: 4px;
    white-space: nowrap;
    z-index: 99999;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.3);
    pointer-events: none;
    transform: translateY(-50%);
    animation: fadeInTooltipRight 0.2s ease;
}

/* Tooltip左侧箭头 */
.global-step-tooltip .tooltip-arrow {
    position: absolute;
    right: 100%;
    top: 50%;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border: 6px solid transparent;
    border-right-color: #303133;
}

/* Tooltip淡入动画 */
@keyframes fadeInTooltipRight {
    from {
        opacity: 0;
        transform: translateY(-50%) translateX(-5px);
    }
    to {
        opacity: 1;
        transform: translateY(-50%) translateX(0);
    }
}

/* 标签页内容容器 - 支持垂直滚动 */
.tab-content-container {
    overflow-y: auto;
    overflow-x: hidden;
    height: 100%;
    max-height: calc(100vh - 400px);  /* 减去页面其他元素的高度 */
    min-height: 300px;
    padding: 10px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    background-color: #fafafa;
}

/* 优化垂直滚动条样式 */
.tab-content-container::-webkit-scrollbar {
    width: 8px;
}

.tab-content-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.tab-content-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.tab-content-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 确保内容在滚动容器内正常显示 */
.tab-content-container > * {
    width: 100%;
}

/* 订单详情区域样式 */
.order-detail-section {
    margin-bottom: 10px;
}

/* 折叠按钮样式优化 */
.order-detail-section + .el-row .el-button--text {
    color: #409EFF;
    font-size: 13px;
}

.order-detail-section + .el-row .el-button--text:hover {
    color: #66b1ff;
}

.order-detail-section + .el-row .el-button--text i {
    font-weight: bold;
    transition: transform 0.3s ease;
}
</style>
